package com.cgnpc.scp.common.service;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

@Service
public class RestTemplateService {
    private static final Logger LOGGER = LoggerFactory.getLogger(RestTemplateService.class);

    @Autowired
    private RestTemplate restTemplate;

    public <T> ResponseEntity<T> postRequest(
            String url,
            Object requestEntity,
            ParameterizedTypeReference<T> responseType
    ) {
        HttpEntity<Object> reqHttpEntity = new HttpEntity<>(requestEntity);
        return restTemplate.exchange(
                url
                , HttpMethod.POST
                , reqHttpEntity
                , responseType
        );
    }

    public <T> T postRequestStatusOk(
            String url,
            Object requestEntity,
            ParameterizedTypeReference<T> responseType
    ) {
        ResponseEntity<T> responseEntity = postRequest(url, requestEntity, responseType);

        if (responseEntity.getStatusCode() == HttpStatus.OK) {
            return responseEntity.getBody();
        }

        return null;
    }

}
